package cn.cocho.custom.yunCashierDf.uc.controller;

import cn.cocho.common.web.app.JsonResultContants;
import cn.cocho.common.web.character.DesEncrypt;
import cn.cocho.common.web.jqgrid.JQGridContants;
import cn.cocho.common.web.jqgrid.JQGridPage;
import cn.cocho.common.web.jqgrid.JQGridRules;
import cn.cocho.common.web.jqgrid.JQGridUtils;
import cn.cocho.common.web.utils.JsonResult;
import cn.cocho.custom.yunCashierDf.cache.CacheCtrl;
import cn.cocho.custom.yunCashierDf.common.controller.QRCodeUtil;
import cn.cocho.custom.yunCashierDf.merchant.domain.MerchantInfo;
import cn.cocho.custom.yunCashierDf.merchant.service.MerchantInfoService;
import cn.cocho.custom.yunCashierDf.uc.domain.UcUserInfo;
import cn.cocho.custom.yunCashierDf.uc.domain.UcUserModule;
import cn.cocho.custom.yunCashierDf.uc.service.UserInfoService;
import cn.cocho.custom.yunCashierDf.utils.AppConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller//声明为控制器（使用Controller将该类标记为spring mvc解析的类，类似Struts中的Action）
public class UserInfoController {

    @Autowired
    UserInfoService userService;

    @Autowired
    CacheCtrl cacheCtrl;

    @Autowired
    private MerchantInfoService merchantInfoService;

    @ResponseBody
    @RequestMapping(value = "/anonymous/uc/loginUserWithVerifyCode")
    public JsonResult loginUserWithVerifyCode(String username, String password, String codeKey, String codeContent) {
        JsonResult result;
        if (cacheCtrl.getVerifyCodeCtrl().checkVerifyCode(codeKey, codeContent)) {//验证码正确
            result = userService.loginUser(username, password);
        } else {
            result = new JsonResult(JsonResultContants.FAIL, JsonResultContants.VERIFY_CODE_FAIL_MSG);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/anonymous/uc/regUser")
    public JsonResult regUser(UcUserInfo userInfo, String codeKey, String codeContent) {
        JsonResult result;
        if (cacheCtrl.getVerifyCodeCtrl().checkVerifyCode(codeKey, codeContent)) {//验证码正确
            result = userService.regUser(userInfo);
        } else {
            result = new JsonResult(JsonResultContants.FAIL, JsonResultContants.VERIFY_CODE_FAIL_MSG);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/anonymous/uc/findPasswordUser")
    public JsonResult findPasswordUser(String email, String codeKey, String codeContent) {
        JsonResult result;
        if (cacheCtrl.getVerifyCodeCtrl().checkVerifyCode(codeKey, codeContent)) {//验证码正确
            result = userService.findPasswordUser(email);
        } else {
            result = new JsonResult(JsonResultContants.FAIL, JsonResultContants.VERIFY_CODE_FAIL_MSG);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/user/uc/updatePassword")
    public JsonResult updatePassword(String currentPassword, String password1, String password2) {
        JsonResult result;
        if (cacheCtrl.getCurrentUcUserInfo().getUserPassword().equals(DesEncrypt.encrypt(currentPassword, AppConstants.PASSWORD_DES))) {
            if (userService.updatePassword(password1)) {
                result = new JsonResult(JsonResultContants.SUCCESS, "密码修改成功！");
            } else {
                result = new JsonResult(JsonResultContants.FAIL, "密码修改失败！");
            }
        } else {
            result = new JsonResult(JsonResultContants.FAIL, "当前密码错误！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/getUserInfoList")
    public JQGridPage getUserInfoList(JQGridPage<UcUserInfo> pageJQGrid) {
        return userService.getListByJQgrid(pageJQGrid);
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/getModuleListByJQgrid")
    public JQGridPage getModuleListByJQgrid(JQGridPage<UcUserModule> pageJQGrid) {
        return userService.getModuleListByJQgrid(pageJQGrid);
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/editUserInfo")
    public void editUserInfo(UcUserInfo userInfo, HttpServletResponse response) {
        String warnMessage = null;
        if (userInfo.getOper().equals(JQGridContants.EDIT_OPER_ADD)) {
            userService.add(userInfo);
        } else if (userInfo.getOper().equals(JQGridContants.EDIT_OPER_UPDATE)) {
            userInfo.setUserId(userInfo.getId());
            userService.update(userInfo);
        } else if (userInfo.getOper().equals(JQGridContants.EDIT_OPER_DEL)) {
            JQGridUtils.delete("delete from uc_user_info where user_id ", userInfo.getId());
        }
        JQGridUtils.warnUserMessage(warnMessage, response);
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/getUserInfoById")
    public JsonResult<UcUserInfo> getUserInfoById(String userId) {
        JsonResult<UcUserInfo> result;
        UcUserInfo ucUserInfo = userService.getUserInfoById(userId);
        ucUserInfo.setUserPassword(DesEncrypt.decrypt(ucUserInfo.getUserPassword(),AppConstants.PASSWORD_DES));
        if (ucUserInfo != null) {
            result = new JsonResult<UcUserInfo>(JsonResultContants.SUCCESS, "获取用户信息成功！", ucUserInfo);
        } else {
            result = new JsonResult<UcUserInfo>(JsonResultContants.FAIL, "无法获取用户信息！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/saveUserInfo")
    public JsonResult saveUserInfo(UcUserInfo ucUserInfo,HttpServletRequest request) {
        JsonResult result;
        //if (StringUtils.isEmpty(ucUserInfo.getUserId())) { //新增
        List<UcUserInfo> listUser = userService.userNameCheck(ucUserInfo.getUsername());
        if(listUser.size() <= 0){

            //调用生成二维码的功能
            String local = request.getRealPath("/") + "/shQrcode";
            String localUrl = null;
            String qrcode = request.getScheme() + "://" + request.getServerName() +"/control/phone/customerPay.jsp?merchantId="+ucUserInfo.getMerchantId()+"&terminalid="+ucUserInfo.getUsername()+"";
            System.out.println(local);

            MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(ucUserInfo.getMerchantId());
            System.out.println(merchantInfo.getMerchantName());

            try {
                localUrl = QRCodeUtil.encode(qrcode, local, merchantInfo.getMerchantName() + "-" + ucUserInfo.getUsername(), true);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String QRcodeUrl = request.getScheme() + "://" + request.getServerName()  + "/shQrcode/" + localUrl;
            ucUserInfo.setQrcode(QRcodeUrl);

            boolean insertResult = userService.insertUserInfo(ucUserInfo);
            if (insertResult == true) {
                result = new JsonResult(JsonResultContants.SUCCESS, "新增用户信息成功！", ucUserInfo.getUserId());
            } else {
                result = new JsonResult(JsonResultContants.FAIL, "新增用户信息失败！");
            }
        }else{
            result = new JsonResult(JsonResultContants.FAIL, "用户名已存在！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/updateUserInfo")
    public JsonResult updateUserInfo(UcUserInfo ucUserInfo,HttpServletRequest request) {
        JsonResult result;
        //调用生成二维码的功能
        String local = request.getRealPath("/") + "/shQrcode";
        String localUrl = null;
        String qrcode = request.getScheme() + "://" + request.getServerName() +"/control/phone/customerPay.jsp?merchantId="+ucUserInfo.getMerchantId()+"&terminalid="+ucUserInfo.getUsername()+"";
        System.out.println(local);

        //查询出商户名称
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(ucUserInfo.getMerchantId());
        System.out.println(merchantInfo.getMerchantName());

        try {
            localUrl = QRCodeUtil.encode(qrcode, local, merchantInfo.getMerchantName() + "-" + ucUserInfo.getUsername(), true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String QRcodeUrl = request.getScheme() + "://" + request.getServerName()  + "/shQrcode/" + localUrl;
        ucUserInfo.setQrcode(QRcodeUrl);
        boolean replaceResult = userService.replaceUserInfo(ucUserInfo);
        if (replaceResult) {
            result = new JsonResult(JsonResultContants.SUCCESS, "修改用户信息成功！", ucUserInfo.getUserId());
        } else {
            result = new JsonResult(JsonResultContants.FAIL, "修改用户信息失败！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/getUserInfo")
    public JsonResult getUserInfo() {
        List<UcUserInfo> list = userService.getUserInfo();
        JsonResult result = new JsonResult(JsonResultContants.SUCCESS, "业务员信息获取成功", list);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/getUserInfoByCurrentId", method = RequestMethod.POST)
    public JsonResult<UcUserInfo> getUserInfoByCurrentId() {
        JsonResult<UcUserInfo> result;
        UcUserInfo userInfo = userService.getUserInfoById(cacheCtrl.getTokenCtrl().getCurrentUcUserInfo().getUserId());
        if (userInfo != null) {
            result = new JsonResult<UcUserInfo>(JsonResultContants.SUCCESS, "获取用户信息成功！", userInfo);
        } else {
            result = new JsonResult<UcUserInfo>(JsonResultContants.FAIL, "无法获取用户信息！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/admin/uc/updateUserPassWord")
    public JsonResult updateUserPassWord(UcUserInfo ucUserInfo) {
        JsonResult result;
        //修改密码前先验证原始密码是否正确
        UcUserInfo newUserInfo = userService.getUserInfoById(ucUserInfo.getUserId());
        if(newUserInfo.getUserPassword().equals(DesEncrypt.encrypt(ucUserInfo.getUserPassword(), AppConstants.PASSWORD_DES))){
            ucUserInfo.setUserPassword(ucUserInfo.getMobilePhone());
            boolean insertResult = userService.replaceUserInfo(ucUserInfo);
            if (insertResult == true) {
                result = new JsonResult(JsonResultContants.SUCCESS, "修改密码信息成功！", ucUserInfo.getUserId());
            } else {
                result = new JsonResult(JsonResultContants.FAIL, "修改密码信息失败！");
            }
        }else{
            result = new JsonResult(JsonResultContants.FIND_PASSWORD_FAIL_MSG, "原始密码输入错误！");
        }
        return result;
    }
}
